
import sublime
import sublime_plugin

import getpass
import time
import re
import os

# 生成lua_snippet
class wlgame_generate_snippetCommand(sublime_plugin.TextCommand):

	def isSysFuncs(self, line):
		sysFuncs = [
			"onCreate",
			"activate",
			"deactivate",
			"onActivate",
			"isActivate",
			"backEvent",
			"initView",
			"initViews",
			"ctor",
			"dtor",
			"onEnter",
			"onExit",
			"initWithFilePath",
			"init",
			"getPartId",
			"getResourceNode",
			"createResourceNode",
			"createResourceBinding",
			"showWithScene",
			"onCleanup",
			"bindPart",
			"onCleanup",
			"addPart",
		]
		isSysFuncs = False
		for i in range(len(sysFuncs)):
			try:
				if line.index(sysFuncs[i]):
					isSysFuncs = True
					break
			except:
				a = 0

		return isSysFuncs

	def replaceIfInstance(self, content):
		listData = [
			["UserData:", "ht.UserData.instance():"],
			["GameListData:", "ht.GameListData.instance():"],
			["GameUser:", "global:getGameUser():"],
			["AppData.", "ht.AppData."],
			["Utils.showTips", "ht.Utils.showTips"],
			["Utils.showMessageBox", "ht.Utils.showMessageBox"],
			["Utils.log", "ht.Utils.log"],
			["Utils.saveNodeAsImage", "ht.Utils.saveNodeAsImage"],
			["UmengReport.", "ht.UmengReport."],
			["OnlineService.", "ht.OnlineService."],
			["WXShareManager:", "ht.WXShareManager:"],
		]
		for i in range(len(listData)):
			try:
				if content.index(listData[i][0]) >= 0:
					content = content.replace(listData[i][0], listData[i][1])
					break
			except:
				# print("[Warning] Can not find " + listData[i])
				a = 0

		return content

	def replaceArguments(self, line, tpl, description):
		print("replaceArguments: ", line)
		content = line.replace(" ", "").replace("function", "").replace(",", ", ")
		content = self.replaceIfInstance(content)
		tpl = tpl.replace("{content}", content)

		index = 0
		try:
			index = line.index(":")
		except:
			index = line.index(".")

		tabTrigger = line[index+1:line.index("(")]
		tabTrigger = tabTrigger.replace(" ", "").replace("function", "")
		tpl = tpl.replace("{tabTrigger}", tabTrigger)

		tpl = tpl.replace("{description}", description)
		return tpl

	def formatFileName(self, filename):
		return filename.replace(" ", "").replace("function", "").replace(".", "_").replace(":", ".")

	def generateSnippetFile(self, targetDir, line, description):
		index = line.index("(")
		filename = line[0:index]
		filename = self.formatFileName(filename) + ".sublime-snippet"
		targetFilePath = os.path.join(targetDir, filename)
		# print(targetFilePath)

		snippetContent = "<snippet><content><![CDATA[{content}]]></content><tabTrigger>{tabTrigger}</tabTrigger><scope>source.lua</scope><description>{description}</description></snippet>"
		
		if self.isSysFuncs(line):
			return

		snippetContent = self.replaceArguments(line, snippetContent, description)

		# 目标文件夹不存在，创建文件夹
		if not os.path.exists(targetDir):
			os.makedirs(targetDir)

		f = None
		try:
			f = open(targetFilePath, "w")
			f.write(snippetContent)
		except Exception as e:
			print("[Error] Write snippet failed.")
			raise
		finally:
			if f:
				f.close()
		return

	def run(self, edit):

		view = self.view

		window = self.view.window()
		extVars = window.extract_variables()

		curFilePath = extVars["file"]
		print(curFilePath)

		if not curFilePath.endswith(".lua"):
			print("[Aborted] The current file is not .lua file.")
			return

		curFileDirName = os.path.dirname(curFilePath)
		dirFirstIndex = curFilePath.index("\\src\\app")
		strDir = curFilePath[dirFirstIndex + 1: len(curFileDirName)]
		basename = os.path.basename(curFilePath)

		if not os.path.isfile(curFilePath):
			print("[Error] The file is not exist.")
			return

		targetDir = os.path.join(sublime.packages_path(), "wlgame-plugin/snippet/custom_snippet", strDir, basename)
		print(targetDir)
		fr = open(curFilePath, "r", -1, "utf8")
		lines = fr.readlines()
		pattern = r'function(\s{1,})([a-zA-Z0-9-_.:]{1,})(\s*)\(([a-zA-Z0-9-_.:\s,]*)\)'
		for i in range(len(lines)):
			res = re.search(pattern, lines[i])
			if res:
				# 找到了function行，再搜索描述
				description = ""
				# for k in range(i, 5, -1):
				# 	try:
				# 		tmp = lines[k].replace(" ", "")
				# 		if tmp.find("@brief") >= 0 and tmp.startswith("--"):
				# 			description = tmp.replace("@brief", "").replace("--", "").replace("---", "")   
				# 			print("description: ", description)
				# 			break
				# 		elif tmp.find("end") >= 0:
				# 			break
				# 		else:
				# 			pass
				# 	except Exception as ex:
				# 		pass
				line = res.group()
				self.generateSnippetFile(targetDir, line, description)